package com.dhcc.sds.busi.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.dhcc.cdc.busi.service.ICdcEpisodeService;
import com.dhcc.cdc.busi.service.ICdcLocationService;
import com.dhcc.cdc.sys.cache.config.CdcConfigCache;
import com.dhcc.cdc.sys.entity.DictionaryEntity;
import com.dhcc.cdc.sys.service.IDictionaryService;
import com.dhcc.core.framework.util.CommonUtil;
import com.dhcc.sds.base.cache.qcentity.QcEntityCache;
import com.dhcc.sds.base.dao.SdsQcentityMapper;
import com.dhcc.sds.base.entity.SdsQcentityEntity;
import com.dhcc.sds.base.service.ISdsCommonService;
import com.dhcc.sds.base.service.ISdsQcentityService;
import com.dhcc.sds.busi.dao.AnalysisSdsMstaMapper;
import com.dhcc.sds.busi.dto.AnalysisCaseDto;
import com.dhcc.sds.busi.dto.AnalysisSdsMstaDto;
import com.dhcc.sds.busi.dto.AnalysisSdsMstaLocDto;
import com.dhcc.sds.busi.dto.AnalysisSdsMstaUpTimeDto;
import com.dhcc.sds.busi.service.IAnalysisSdsMstaService;
import com.dhcc.sds.busi.service.ISdsQcincaseService;
import com.dhcc.sds.busi.vo.AnalysisSdsPortalVo;
import com.dhcc.sds.util.StrUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author zhangdc
 * @version 1.0
 * @date 2021/6/28 15:08
 */
@Service
public class AnalysisSdsMstaServiceImpl implements IAnalysisSdsMstaService {

    @Autowired
    private ISdsCommonService sdsCommonService;

    @Autowired
    private ICdcEpisodeService cdcEpisodeService;

    @Autowired
    private ICdcLocationService cdcLocationService;

    @Autowired
    private ISdsQcincaseService sdsQcincaseService;

    @Resource
    private AnalysisSdsMstaMapper analysisSdsMstaMapper;

    @Autowired
    private ISdsQcentityService sdsQcentityService;

    @Autowired
    private IDictionaryService dictionaryService;

    @Autowired
    private SdsQcentityMapper sdsQcentityMapper;

    @Override
    public JSONObject selectSdsMsta(Map<String, Object> params) {
        JSONObject caseDataObj = new JSONObject();
        JSONArray chartDatas = new JSONArray();

        List<AnalysisSdsMstaDto> statisList = analysisSdsMstaMapper.selectMstaDataByLoc(params);
        for (AnalysisSdsMstaDto analysisSdsMstaDto : statisList) {
            Long entityId = analysisSdsMstaDto.getEntityId();
            SdsQcentityEntity sdsQcentityEntity = sdsQcentityService.selectById(entityId);
            if (sdsQcentityEntity.getIsActive()==3) {// 如果病种状态是灰色，不参与统计
                statisList.remove(analysisSdsMstaDto);
                continue;
            }
            analysisSdsMstaDto.setEntityDesc(sdsQcentityEntity.getBtDesc());
            Integer hosDays = analysisSdsMstaDto.getHosDays();
            Float hosCost = analysisSdsMstaDto.getHosCost();
            Float consumCost1 = analysisSdsMstaDto.getConsumCost1();
            Float consumCost2 = analysisSdsMstaDto.getConsumCost2();
            Float consumCost3 = analysisSdsMstaDto.getConsumCost3();
            Float consumCost4 = analysisSdsMstaDto.getConsumCost4();
            Float consumCost = consumCost1 + consumCost2 + consumCost3 + consumCost4;
            Float medeCost = analysisSdsMstaDto.getMedeCost();
            Integer consistentNum = analysisSdsMstaDto.getConsistentNum();
            if (!Objects.equals(0, consistentNum)) {
                DecimalFormat df = new DecimalFormat("0.00");
                String averageHosDays = df.format((float) hosDays / consistentNum);
                String averageHosCost = df.format(hosCost / consistentNum);
                String averageMedeCost = df.format(medeCost / consistentNum);
                String averageConsumCost = df.format(consumCost / consistentNum);
                analysisSdsMstaDto.setAverageHosDays(averageHosDays);
                analysisSdsMstaDto.setAverageHosCost(averageHosCost);
                analysisSdsMstaDto.setAverageMedeCost(averageMedeCost);
                analysisSdsMstaDto.setAverageConsumCost(averageConsumCost);
            }
        }

        List<AnalysisSdsMstaDto> charList = analysisSdsMstaMapper.selectMstaDataForChart(params);
        JSONArray confirmRate = new JSONArray();//上报率
        for (AnalysisSdsMstaDto analysisSdsMstaDto : charList) {
            confirmRate.add(splitJSONObj(analysisSdsMstaDto.getLocDesc(), StrUtil.deciFormatU(analysisSdsMstaDto.getReported(), analysisSdsMstaDto.getConsistentNum()), "confirmRate"));

        }
        chartDatas.add(confirmRate);

        caseDataObj.put("chartDatas", chartDatas);
        caseDataObj.put("tableDates", statisList);

        return caseDataObj;
    }

    @Override
    public JSONObject selectSdsUpData(Map<String, Object> params) {
        /*String startDate = (String) params.get("startDate");
        String endDate = (String) params.get("endDate");*/
        String month = (String) params.get("month");
        String year = (String) params.get("year");
        if (!StringUtils.isEmpty(month)) {
            String month2 = year + "-" + month;
            params.put("month", month2);
        }
        String office = (String) params.get("office");
        String depart = (String) params.get("depart");
        String qcEntity = (String) params.get("qcEntity");

        JSONObject caseObj = new JSONObject();
        //图一
        //TODO:昨日上报、上个月上报、上一年年上报
        //今天
        DateTime startDateDay = DateUtil.beginOfDay(new Date());
        DateTime endDateDay = DateUtil.endOfDay(new Date());
        //昨天
        DateTime startDateLastDay = com.dhcc.sds.util.DateUtil.getDateByDay(startDateDay, -1);
        DateTime endDateLastDay = com.dhcc.sds.util.DateUtil.getDateByDay(endDateDay, -1);
        //本月
        DateTime startDateMonth = DateUtil.beginOfMonth(new Date());
        DateTime endDateMonth = DateUtil.endOfMonth(new Date());
        //上月
        DateTime startDateLastMonth = com.dhcc.sds.util.DateUtil.getDateByMonth(startDateMonth, -1);
        DateTime endDateLastMonth = com.dhcc.sds.util.DateUtil.getDateByMonth(endDateMonth, -1);
        //本年
        DateTime startDateYear = DateUtil.beginOfYear(new Date());
        DateTime endDateYear = DateUtil.endOfYear(new Date());
        //去年
        DateTime startDateLastYear = com.dhcc.sds.util.DateUtil.getDateByYear(startDateYear, -1);
        DateTime endDateLastYear = com.dhcc.sds.util.DateUtil.getDateByYear(endDateYear, -1);

        int sdsQcincaseEntitiesDay = analysisSdsMstaMapper.selectUpDataByTime(startDateDay, endDateDay);
        int sdsQcincaseEntitiesMonth = analysisSdsMstaMapper.selectUpDataByTime(startDateMonth, endDateMonth);
        int sdsQcincaseEntitiesYear = analysisSdsMstaMapper.selectUpDataByTime(startDateYear, endDateYear);

        int sdsQcincaseEntitiesLastDay = analysisSdsMstaMapper.selectUpDataByTime(startDateLastDay, endDateLastDay);
        int sdsQcincaseEntitiesLastMonth = analysisSdsMstaMapper.selectUpDataByTime(startDateLastMonth, endDateLastMonth);
        int sdsQcincaseEntitiesLastYear = analysisSdsMstaMapper.selectUpDataByTime(startDateLastYear, endDateLastYear);

        int sdsQcincaseEntitiesAll = analysisSdsMstaMapper.selectUpDataByTime(null, null);
        caseObj.put("todayUp", sdsQcincaseEntitiesDay);//今日上报
        caseObj.put("todayUpRate", StrUtil.ringRatio(sdsQcincaseEntitiesDay, sdsQcincaseEntitiesLastDay));//今日上报环比
        caseObj.put("monthUp", sdsQcincaseEntitiesMonth);//本月上报
        caseObj.put("monthUpRate", StrUtil.ringRatio(sdsQcincaseEntitiesMonth, sdsQcincaseEntitiesLastMonth));//本月上报环比
        caseObj.put("yearUp", sdsQcincaseEntitiesYear);//本年上报
        caseObj.put("yearUpRate", StrUtil.ringRatio(sdsQcincaseEntitiesYear, sdsQcincaseEntitiesLastYear));//本年上报环比
        caseObj.put("totalUp", sdsQcincaseEntitiesAll);//累计上报
        //caseObj.put("totalUpRate", "41.2%");
        //图上报例数
        JSONArray upNumChart = new JSONArray();
        JSONArray chartDatas = new JSONArray();
        List<AnalysisSdsMstaUpTimeDto> analysisSdsMstaUpYearDtos = new ArrayList<>();
        /*int syear = 0;
        int eyear = 1;
        if (!StringUtils.isEmpty(startDate)){
            DateTime sDate = DateUtil.parse(startDate);
            DateTime eDate = DateUtil.parse(endDate);
            syear = DateUtil.year(sDate);
            eyear = DateUtil.year(eDate);
        }
        if (Objects.equals(syear, eyear)){
            //坐标为月
            analysisSdsMstaUpYearDtos = analysisSdsMstaMapper.selectUpDataByMonth(params);
        }else {
            //坐标为年
            analysisSdsMstaUpYearDtos = analysisSdsMstaMapper.selectUpDataByYear(params);
        }*/
        if (Objects.equals("全部", year)) {
            //坐标为年
            analysisSdsMstaUpYearDtos = analysisSdsMstaMapper.selectUpDataByYear(params);
        } else {
            //坐标为月
            analysisSdsMstaUpYearDtos = analysisSdsMstaMapper.selectUpDataByMonth(params);
        }

        for (AnalysisSdsMstaUpTimeDto analysisSdsMstaUpTimeDto : analysisSdsMstaUpYearDtos) {
            upNumChart.add(splitJSONObj(analysisSdsMstaUpTimeDto.getTime(), analysisSdsMstaUpTimeDto.getTotal(), "upNum"));
        }
        chartDatas.add(upNumChart);
        caseObj.put("chartDatas", chartDatas);
        //图三
        /*AnalysisSdsMstaUpRateDto analysisSdsMstaUpRateDto = analysisSdsMstaMapper.selectUpDataRate(params);
        caseObj.put("upLoc", analysisSdsMstaUpRateDto.getLocNum());
        caseObj.put("upEntity", analysisSdsMstaUpRateDto.getUpEntityNum());
        caseObj.put("upEntityRate", deciFormat(analysisSdsMstaUpRateDto.getUpEntityNum(), analysisSdsMstaUpRateDto.getEntityNum()));
        caseObj.put("upTimeRate", "2.2%");*/
        //图病种上报占比
        JSONArray entityTypeData = new JSONArray();
        List<SdsQcentityEntity> list = sdsQcentityService.selectList(null);
        List<AnalysisCaseDto> analysisCaseDtos = analysisSdsMstaMapper.selectUpData(params);
        //List<AnalysisCaseDto> upEntity = new ArrayList<>();
        Set<String> upEntity = new HashSet<>();
        int notUpEntity = list.size();
        for (AnalysisCaseDto analysisCaseDto : analysisCaseDtos) {
            upEntity.add(analysisCaseDto.getEntityCode());
        }
        notUpEntity = list.size() - upEntity.size();
        entityTypeData.add(getJSONObj(2, "name", "上报病种", "value", upEntity.size() + "", "", ""));
        entityTypeData.add(getJSONObj(2, "name", "未上报病种", "value", notUpEntity + "", "", ""));
        caseObj.put("entityTypeData", entityTypeData);
        caseObj.put("upEntity", upEntity.size());
        caseObj.put("allEntity", list.size());
        //图 上报前十病种
        JSONArray upTopEntityData = new JSONArray();
        /*upTopEntityData.add(splitJSONObj("急性心肌梗死", "100", "upTopEntity"));
        upTopEntityData.add(splitJSONObj("心力衰竭", "80", "upTopEntity"));
        upTopEntityData.add(splitJSONObj("急性脑梗死", "60", "upTopEntity"));*/
        List<AnalysisCaseDto> analysisCaseDtos1 = analysisSdsMstaMapper.selectUpTopData(params);
        for (AnalysisCaseDto analysisCaseDto : analysisCaseDtos1) {
            upTopEntityData.add(splitJSONObj(analysisCaseDto.getEntityCode(), analysisCaseDto.getReportedNum(), "upTopEntity"));
        }
        caseObj.put("upTopEntityData", upTopEntityData);

        //图 十日病种上报及时率 及时/全部上报
        JSONArray upTimeEntityData = new JSONArray();
        /*upTimeEntityData.add(splitJSONObj("急性心肌梗死", "60", "upTimeEntity"));
        upTimeEntityData.add(splitJSONObj("心力衰竭", "40", "upTimeEntity"));
        upTimeEntityData.add(splitJSONObj("急性脑梗死", "50", "upTimeEntity"));*/
        Map<String, Integer> map1 = new HashMap<>();
        Map<String, Integer> map2 = new HashMap<>();
        List<AnalysisSdsPortalVo> analysisSdsPortalVoList = new ArrayList<>();
        String baseDateForDelayed = CdcConfigCache.me().getValueByKey("SDS", "BaseDateForDelayed", "2");
        for (AnalysisCaseDto analysisCaseDto : analysisCaseDtos) {
            AnalysisSdsPortalVo analysisSdsPortalVo = new AnalysisSdsPortalVo();
            analysisCaseDto.getEntityId();
            analysisCaseDto.getDishDate();
            analysisCaseDto.getEntityUpDate();
            analysisCaseDto.getEntityCode();
            Long d = 0l;
            if (CommonUtil.equals(baseDateForDelayed, "1")) {
                if (!StringUtils.isEmpty(analysisCaseDto.getDishDate()) && !StringUtils.isEmpty(analysisCaseDto.getEntityUpDate())) {
                    d = com.dhcc.sds.util.DateUtil.getDateCompare(analysisCaseDto.getEntityUpDate(), analysisCaseDto.getDishDate(), "d");
                }
            } else if(CommonUtil.equals(baseDateForDelayed, "2")){
                if (!StringUtils.isEmpty(analysisCaseDto.getCodeDate()) && !StringUtils.isEmpty(analysisCaseDto.getEntityUpDate())) {
                    d = com.dhcc.sds.util.DateUtil.getDateCompare(analysisCaseDto.getEntityUpDate(), analysisCaseDto.getCodeDate(), "d");
                }
            } else if(CommonUtil.equals(baseDateForDelayed, "3")){
                if (!StringUtils.isEmpty(analysisCaseDto.getCodeDate()) && !StringUtils.isEmpty(analysisCaseDto.getEntityUpDate())) {
                    d = com.dhcc.sds.util.DateUtil.getDateCompare(analysisCaseDto.getEntityUpDate(), analysisCaseDto.getInDateTime(), "d");
                }
            }
            //全部上报
            Integer i = map1.get(analysisCaseDto.getEntityCode());
            if (StringUtils.isEmpty(i)) {
                map1.put(analysisCaseDto.getEntityCode(), 1);
                analysisSdsPortalVo.setEntityDesc(analysisCaseDto.getEntityDesc());
                analysisSdsPortalVo.setCode(analysisCaseDto.getEntityCode());
                analysisSdsPortalVoList.add(analysisSdsPortalVo);
            } else {
                map1.put(analysisCaseDto.getEntityCode(), i + 1);
            }
            //及时
            Integer i2 = map2.get(analysisCaseDto.getEntityCode());
            if (StringUtils.isEmpty(i2)) {
                if (d <= 10) {
                    map2.put(analysisCaseDto.getEntityCode(), 1);
                } else {
                    map2.put(analysisCaseDto.getEntityCode(), 0);
                }
            } else {
                if (d <= 10) {
                    map2.put(analysisCaseDto.getEntityCode(), i2 + 1);
                }
            }
        }

        for (AnalysisSdsPortalVo entry : analysisSdsPortalVoList) {
            String key = entry.getCode();
            Integer i1 = map1.get(key);
            Integer i2 = map2.get(key);
//            upTimeEntityData.add(splitJSONObj(key, StrUtil.deciFormatM(i2, i1), "upTimeEntity"));
            entry.setaRatio(StrUtil.deciFormatM(i2, i1));
        }

//        for (HashMap.Entry<String, Integer> entry : map1.entrySet()) {
//            String key = entry.getKey();
//            Integer i1 = map1.get(key);
//            Integer i2 = map2.get(key);
//            upTimeEntityData.add(splitJSONObj(key, StrUtil.deciFormatM(i2, i1), "upTimeEntity"));
//        }
        caseObj.put("upTimeEntityData", analysisSdsPortalVoList);

        /*//表格
        List<AnalysisSdsMstaDto> statisList = analysisSdsMstaMapper.selectMstaDataByEntity(params);
        for (AnalysisSdsMstaDto analysisSdsMstaDto : statisList){
            Long entityId = analysisSdsMstaDto.getEntityId();
            SdsQcentityEntity sdsQcentityEntity = sdsQcentityService.selectById(entityId);
            analysisSdsMstaDto.setEntityDesc(sdsQcentityEntity.getBtDesc());
            Integer hosDays = analysisSdsMstaDto.getHosDays();
            Float hosCost = analysisSdsMstaDto.getHosCost();
            Float consumCost1 = analysisSdsMstaDto.getConsumCost1();
            Float consumCost2 = analysisSdsMstaDto.getConsumCost2();
            Float consumCost3 = analysisSdsMstaDto.getConsumCost3();
            Float consumCost4 = analysisSdsMstaDto.getConsumCost4();
            Float consumCost = consumCost1 + consumCost2 + consumCost3 + consumCost4;
            Float medeCost = analysisSdsMstaDto.getMedeCost();
            Integer consistentNum = analysisSdsMstaDto.getConsistentNum();
            if (!Objects.equals(0, consistentNum)){
                DecimalFormat df = new DecimalFormat("0.00");
                String averageHosDays = df.format((float)hosDays/consistentNum);
                String averageHosCost = df.format(hosCost/consistentNum);
                String averageMedeCost = df.format(medeCost/consistentNum);
                String averageConsumCost = df.format(consumCost/consistentNum);
                analysisSdsMstaDto.setAverageHosDays(averageHosDays);
                analysisSdsMstaDto.setAverageHosCost(averageHosCost);
                analysisSdsMstaDto.setAverageMedeCost(averageMedeCost);
                analysisSdsMstaDto.setAverageConsumCost(averageConsumCost);
            }
        }
        caseObj.put("tableDates", statisList);*/

        return caseObj;

    }

    @Override
    public List<AnalysisCaseDto> caselist(Page<AnalysisCaseDto> page, Map<String, Object> params) {
        String key = (String) params.get("key");
        String month = (String) params.get("month");
        String year = (String) params.get("year");
        if (!StringUtils.isEmpty(month)) {
            String month2 = year + "-" + month;
            params.put("month", month2);
        }
        List<AnalysisCaseDto> analysisCaseDtos = new ArrayList<>();
        String sqlStr = getSqlStr(key, params);
        // searchType为3，代表是从科室组统计页面钻取，需要把locid转换为实际关联科室id
        if (CommonUtil.equals(params.get("searchType"), "3")) {
            if (CommonUtil.isNotEmpty(params.get("locId"))) {
                List<String> detpIds = analysisSdsMstaMapper.selectDeptIdByGroupId(Long.valueOf(params.get("locId").toString()));
                params.put("userLinkDepts", detpIds);
            }
            params.remove("locId");
        }
        analysisCaseDtos = analysisSdsMstaMapper.selectTableCase(sqlStr, page, params);

        return analysisCaseDtos;
    }

    /**
     * 根据图例名称 返回查询SQL
     */
    public String getSqlStr(String key, Map<String, Object> params){
        String sqlStr = "";
        switch (key) {
            case "consistentNum":
                sqlStr = "and A.state != 'O'";
                break;
            case "than10DaysNoReport":
                sqlStr = "and A.state != 'Up' and DATEDIFF(CURRENT_DATE, A.in_date) > 10";
                break;
            case "in10DaysReported":
                sqlStr = "and A.state = 'Up' and DATEDIFF(A.oper_date, A.in_date) <= 10";
                break;
            case "reported":
            case "totalUp":
                sqlStr = "and A.state = 'Up'";
                break;
            case "noReport":
                sqlStr = "and A.state != 'Up'";
                break;
            case "unfill":
                sqlStr = "and (A.state = 'I' OR A.state = 'Save')";
                break;
            case "submited":
                sqlStr = "and A.state = 'Submit'";
                break;
            case "checked":
                sqlStr = "and A.state = 'Check'";
                break;
            case "backed":
                sqlStr = "and A.state = 'Back'";
                break;
            case "deathNum":
                sqlStr = "and ep.is_death = 1";
                break;
            case "complicationRate":
                sqlStr = "AND B.in_case_id IS NOT NULL";
                break;
            default:
                break;
        }
        return sqlStr;
    }

    @Override
    public JSONObject selectSdsMstaDepart(Map<String, Object> params) {
        JSONObject departDataObj = new JSONObject();
        JSONObject chartDatas = new JSONObject();
        String key = (String) params.get("key");

        List<AnalysisSdsMstaDto> statisList = new ArrayList<>();
        List<AnalysisSdsMstaDto> charList = new ArrayList<>();
        JSONArray confirmRate = new JSONArray();
        if (Objects.equals("upEntity", key)) {
            //显示上报病种
            statisList = analysisSdsMstaMapper.selectMstaDataByEntity(params);

            for (AnalysisSdsMstaDto analysisSdsMstaDto : statisList) {
                Long entityId = analysisSdsMstaDto.getEntityId();
                SdsQcentityEntity sdsQcentityEntity = sdsQcentityService.selectById(entityId);
                //analysisSdsMstaDto.setEntityDesc(sdsQcentityEntity.getBtDesc());
                confirmRate.add(splitJSONObj(sdsQcentityEntity.getBtDesc(), StrUtil.deciFormatU(analysisSdsMstaDto.getReported(), analysisSdsMstaDto.getConsistentNum()), "confirmRate"));
            }
        } else if (Objects.equals("upLoc", key)) {
            //显示上报科室
            statisList = analysisSdsMstaMapper.selectMstaDataByLoc(params);

            charList = analysisSdsMstaMapper.selectMstaDataForChart(params);
            for (AnalysisSdsMstaDto analysisSdsMstaDto : charList) {
                confirmRate.add(splitJSONObj(analysisSdsMstaDto.getLocDesc(), StrUtil.deciFormatU(analysisSdsMstaDto.getReported(), analysisSdsMstaDto.getConsistentNum()), "confirmRate"));
            }
        }

        for (AnalysisSdsMstaDto analysisSdsMstaDto : statisList) {
            Long entityId = analysisSdsMstaDto.getEntityId();
            SdsQcentityEntity sdsQcentityEntity = sdsQcentityService.selectById(entityId);
            analysisSdsMstaDto.setEntityDesc(sdsQcentityEntity.getBtDesc());
            Integer hosDays = analysisSdsMstaDto.getHosDays();
            Float hosCost = analysisSdsMstaDto.getHosCost();
            Float consumCost1 = analysisSdsMstaDto.getConsumCost1();
            Float consumCost2 = analysisSdsMstaDto.getConsumCost2();
            Float consumCost3 = analysisSdsMstaDto.getConsumCost3();
            Float consumCost4 = analysisSdsMstaDto.getConsumCost4();
            Float consumCost = consumCost1 + consumCost2 + consumCost3 + consumCost4;
            Float medeCost = analysisSdsMstaDto.getMedeCost();
            Integer consistentNum = analysisSdsMstaDto.getConsistentNum();
            if (!Objects.equals(0, consistentNum)) {
                DecimalFormat df = new DecimalFormat("0.00");
                String averageHosDays = df.format((float) hosDays / consistentNum);
                String averageHosCost = df.format(hosCost / consistentNum);
                String averageMedeCost = df.format(medeCost / consistentNum);
                String averageConsumCost = df.format(consumCost / consistentNum);
                analysisSdsMstaDto.setAverageHosDays(averageHosDays);
                analysisSdsMstaDto.setAverageHosCost(averageHosCost);
                analysisSdsMstaDto.setAverageMedeCost(averageMedeCost);
                analysisSdsMstaDto.setAverageConsumCost(averageConsumCost);
            }
        }

        confirmRate.sort(Comparator.comparing(obj -> ((JSONObject) obj).getBigDecimal("confirmRate")).reversed());
        chartDatas.put("confirmRate", confirmRate);

        departDataObj.put("chartDatas", chartDatas);
        departDataObj.put("tableDates", statisList);
        return departDataObj;
    }

    @Override
    public JSONObject selectSdsMstaTable(Map<String, Object> params) {
        JSONObject caseObj = new JSONObject();

        // 获取重点病种列表
        if (CommonUtil.isNotEmpty(params.get("keyDisease"))) {
            String keyDisease = params.get("keyDisease").toString();
            String keyDiseaseCodeStr;
            String keyDiseaseIdStr = "";
            if ("1".equals(keyDisease)) {
                keyDiseaseCodeStr = CdcConfigCache.me().getValueByKey("SDS", "NationalExamDisease");
            } else {
                keyDiseaseCodeStr = CdcConfigCache.me().getValueByKey("SDS", "KeyDeptDisease");
            }
            // 获取病种ID
            for (String diseaseCode : keyDiseaseCodeStr.split(",")) {
                SdsQcentityEntity qcentity = new SdsQcentityEntity();
                qcentity.setAbbrev(diseaseCode);
                qcentity = sdsQcentityMapper.selectOne(qcentity);
                if (qcentity!=null) {
                    keyDiseaseIdStr += qcentity.getId() + ",";
                }
            }
            params.put("qcEntity", keyDiseaseIdStr);
        }

        String month = (String) params.get("month");
        String year = (String) params.get("year");
        if (!StringUtils.isEmpty(month)) {
            String month2 = year + "-" + month;
            params.put("month", month2);
        }

        //表格
        List<AnalysisSdsMstaDto> statisList = analysisSdsMstaMapper.selectMstaDataByEntity(params);
        Iterator<AnalysisSdsMstaDto> itr = statisList.iterator();
        while (itr.hasNext()) {
            AnalysisSdsMstaDto analysisSdsMstaDto = itr.next();
            Long entityId = analysisSdsMstaDto.getEntityId();
            SdsQcentityEntity sdsQcentityEntity = sdsQcentityService.selectById(entityId);
            if (sdsQcentityEntity.getIsActive()==3) {// 如果病种状态是灰色，不参与统计
                itr.remove();
                continue;
            }
            analysisSdsMstaDto.setEntityDesc(sdsQcentityEntity.getBtDesc());
            Integer hosDays = analysisSdsMstaDto.getHosDays();
            Float hosCost = analysisSdsMstaDto.getHosCost();
            Float consumCost1 = analysisSdsMstaDto.getConsumCost1();
            Float consumCost2 = analysisSdsMstaDto.getConsumCost2();
            Float consumCost3 = analysisSdsMstaDto.getConsumCost3();
            Float consumCost4 = analysisSdsMstaDto.getConsumCost4();
            Float consumCost = consumCost1 + consumCost2 + consumCost3 ;
            analysisSdsMstaDto.setConsumCost(consumCost);
            Float medeCost = analysisSdsMstaDto.getMedeCost();
            Integer consistentNum = analysisSdsMstaDto.getConsistentNum();
            if (!Objects.equals(0, consistentNum)) {
                DecimalFormat df = new DecimalFormat("0.00");
                String averageHosDays = df.format((float) hosDays / consistentNum);
                String averageHosCost = df.format(hosCost / consistentNum);
                String averageMedeCost = df.format(medeCost / consistentNum);
                String averageConsumCost = df.format(consumCost / consistentNum);
                analysisSdsMstaDto.setAverageHosDays(averageHosDays);
                analysisSdsMstaDto.setAverageHosCost(averageHosCost);
                analysisSdsMstaDto.setAverageMedeCost(averageMedeCost);
                analysisSdsMstaDto.setAverageConsumCost(averageConsumCost);
            }
        }
        caseObj.put("tableDates", statisList);

        //图
        JSONArray hosDaysData = new JSONArray();
        JSONArray hosCostData = new JSONArray();
        double hosDays1 = 0;
        double hosCost1 = 0;
        double hosDays2 = 0;
        double hosCost2 = 0;
        double hosDays3 = 0;
        double hosCost3 = 0;
        double hosDays4 = 0;
        double hosCost4 = 0;
        double hosDays5 = 0;
        double hosCost5 = 0;
        double hosDays6 = 0;
        double hosCost6 = 0;
        double hosDays7 = 0;
        double hosCost7 = 0;
        for (AnalysisSdsMstaDto analysisSdsMstaDto : statisList) {
            SdsQcentityEntity sdsQcentityEntity = sdsQcentityService.selectById(analysisSdsMstaDto.getEntityId());
            if (sdsQcentityEntity.getIsActive()==3) {// 如果病种状态是灰色，不参与统计
                statisList.remove(analysisSdsMstaDto);
                continue;
            }
            if (!StringUtils.isEmpty(sdsQcentityEntity)) {
                DictionaryEntity dictionaryEntity = dictionaryService.selectById(sdsQcentityEntity.getEntityCatId());
                if (!StringUtils.isEmpty(dictionaryEntity)) {
                    String description = dictionaryEntity.getDescription();
                    String averageHosDays = analysisSdsMstaDto.getAverageHosDays();
                    if (CommonUtil.isEmpty(averageHosDays)) {
                        averageHosDays = "0";
                    }
                    String averageHosCost = analysisSdsMstaDto.getAverageHosCost();
                    if (CommonUtil.isEmpty(averageHosCost)) {
                        averageHosCost = "0";
                    }

                    switch (description) {
                        case "呼吸系统疾病/手术":
                            hosDaysData.add(splitJSONObj(analysisSdsMstaDto.getEntityDesc(), hosDays1 + Double.parseDouble(averageHosDays), "hosDays"));
                            hosCostData.add(splitJSONObj(analysisSdsMstaDto.getEntityDesc(), hosCost1 + Double.parseDouble(averageHosCost), "hosCost"));
                            break;
                        case "神经系统疾病/手术":
                            hosDaysData.add(splitJSONObj(analysisSdsMstaDto.getEntityDesc(), hosDays2 + Double.parseDouble(averageHosDays), "hosDays"));
                            hosCostData.add(splitJSONObj(analysisSdsMstaDto.getEntityDesc(), hosCost2 + Double.parseDouble(averageHosCost), "hosCost"));
                            break;
                        case "生殖系统疾病/手术":
                            hosDaysData.add(splitJSONObj(analysisSdsMstaDto.getEntityDesc(), hosDays3 + Double.parseDouble(averageHosDays), "hosDays"));
                            hosCostData.add(splitJSONObj(analysisSdsMstaDto.getEntityDesc(), hosCost3 + Double.parseDouble(averageHosCost), "hosCost"));
                            break;
                        case "心血管系统疾病/手术":
                            hosDaysData.add(splitJSONObj(analysisSdsMstaDto.getEntityDesc(), hosDays4 + Double.parseDouble(averageHosDays), "hosDays"));
                            hosCostData.add(splitJSONObj(analysisSdsMstaDto.getEntityDesc(), hosCost4 + Double.parseDouble(averageHosCost), "hosCost"));
                            break;
                        case "运动系统疾病/手术":
                            hosDaysData.add(splitJSONObj(analysisSdsMstaDto.getEntityDesc(), hosDays5 + Double.parseDouble(averageHosDays), "hosDays"));
                            hosCostData.add(splitJSONObj(analysisSdsMstaDto.getEntityDesc(), hosCost5 + Double.parseDouble(averageHosCost), "hosCost"));
                            break;
                        case "肿瘤（手术治疗）":
                            hosDaysData.add(splitJSONObj(analysisSdsMstaDto.getEntityDesc(), hosDays6 + Double.parseDouble(averageHosDays), "hosDays"));
                            hosCostData.add(splitJSONObj(analysisSdsMstaDto.getEntityDesc(), hosCost6 + Double.parseDouble(averageHosCost), "hosCost"));
                            break;
                        case "其他疾病/手术":
                            hosDaysData.add(splitJSONObj(analysisSdsMstaDto.getEntityDesc(), hosDays7 + Double.parseDouble(averageHosDays), "hosDays"));
                            hosCostData.add(splitJSONObj(analysisSdsMstaDto.getEntityDesc(), hosCost7 + Double.parseDouble(averageHosCost), "hosCost"));
                            break;
                        default:
                            break;
                    }
                }
            }
        }

        hosDaysData = new JSONArray(hosDaysData.stream().sorted((o1, o2) -> {
            if (o1 instanceof JSONObject && o2 instanceof JSONObject) {
                JSONObject json1 = (JSONObject) o1;
                JSONObject json2 = (JSONObject) o2;
                return (int) Math.floor((double) json2.get("hosDays") - (double) json1.get("hosDays"));
            }
            return 0;
//        }).limit(10).collect(Collectors.toList()));
        }).collect(Collectors.toList()));

        hosCostData = new JSONArray(hosCostData.stream().sorted((o1, o2) -> {
            if (o1 instanceof JSONObject && o2 instanceof JSONObject) {
                JSONObject json1 = (JSONObject) o1;
                JSONObject json2 = (JSONObject) o2;
                return (int) Math.floor((double) json2.get("hosCost") - (double) json1.get("hosCost"));
            }
            return 0;
//        }).limit(10).collect(Collectors.toList()));
        }).collect(Collectors.toList()));

        caseObj.put("hosDaysData", hosDaysData);
        caseObj.put("hosCostData", hosCostData);

        return caseObj;
    }

    /**
     * @Description: 拼接JSON vteEcharts.js
     */
    public JSONObject splitJSONObj(String ddesc, Object rate, String code) {
        JSONObject obj = new JSONObject();
        obj.put("ddesc", ddesc);
        obj.put(code, rate);
        return obj;
    }

    public JSONObject getJSONObj(int keyNum, String key1, String value1, String key2, String value2, String key3, String value3) {
        JSONObject jsonObj = new JSONObject();
        if (keyNum == 2) {
            jsonObj.put(key1, value1);
            jsonObj.put(key2, value2);
        } else if (keyNum == 3) {
            jsonObj.put(key1, value1);
            jsonObj.put(key2, value2);
            jsonObj.put(key3, value3);
        }
        return jsonObj;
    }

    @Override
    public JSONObject selectSdsLocTable(Map<String, Object> params) {
        JSONObject obj = new JSONObject();
        List<AnalysisSdsMstaLocDto> statisList = analysisSdsMstaMapper.selectMstaLocDataByEntity(params);
        obj.put("tableData", statisList);
        return obj;
    }

    @Override
    public JSONObject selectSdsDocTable(Map<String, Object> params) {
        JSONObject obj = new JSONObject();
        List<AnalysisSdsMstaLocDto> statisList = analysisSdsMstaMapper.selectMstaDocDataByLocTable(params);
        obj.put("tableData", statisList);
        return obj;
    }

    @Override
    public JSONObject selectSdsQcDocTable(Map<String, Object> params) {
        JSONObject obj = new JSONObject();
        // 获取全部有效病种
        Long entityTypeId = sdsCommonService.getDictId("QcentityType","Up");
        List<SdsQcentityEntity> qcentityEntities = sdsQcentityMapper.selectList(new EntityWrapper<SdsQcentityEntity>().ne("is_active", 0).eq("entity_type_id",entityTypeId).orderBy("ind_no"));
        String selObjStr = "";
        int i = 2;
        for (SdsQcentityEntity qcentity : qcentityEntities) {
            selObjStr += ",sum( CASE WHEN tscq.bt_desc  = '" + qcentity.getBtDesc() + "' then 1 else 0 end ) as '" + String.format("%02d", i)+"_"+qcentity.getBtDesc() + "' ";
            i++;
        }
        selObjStr += ",COUNT( IFNULL( ql.oper_user, '未知姓名' ) ) as '" + String.format("%02d", i) + "_合计'";
        List<Map<String, Object>> statisList = analysisSdsMstaMapper.selectMstaQcDocData(params, selObjStr);
        obj.put("tableData", statisList);
        return obj;
    }

    @Override
    public JSONObject selectSdsLocGroupTable(Map<String, Object> params) {
        JSONObject obj = new JSONObject();
        List<AnalysisSdsMstaLocDto> statisList = analysisSdsMstaMapper.selectMstaLocGroupData(params);
        obj.put("tableData", statisList);
        return obj;
    }

    @Override
    public JSONObject getReportLocOrGroup(Map<String, Object> params) {
        JSONObject caseDataObj = new JSONObject();
        List<Map<String, Object>> caseDataMap = this.analysisSdsMstaMapper.selectReportLocOrGroupData(params);

        JSONArray chartDatas = new JSONArray();
        JSONArray chartDeathAndSurDatas = new JSONArray();
        JSONArray chartAverHosDatas = new JSONArray();


        JSONArray reportedRate = new JSONArray();//上报率
        JSONArray deathRate = new JSONArray();//死亡率
        JSONArray averageHosDays = new JSONArray();//次均住院日
        JSONArray averageHosCost = new JSONArray();//次均住院费用
        JSONArray averageConsumCost = new JSONArray();//平均耗材费
        JSONArray averageMedeCost = new JSONArray();//平均药费
        JSONArray surgeryRate = new JSONArray(); //手术并发症发生率


        for (Map<String, Object> caseMap : caseDataMap) {
            String ddesc = caseMap.get("locDesc").toString();
            reportedRate.add(splitJSONObj(ddesc, caseMap.get("reportedRate"), "reportedRate"));
            deathRate.add(splitJSONObj(ddesc, caseMap.get("deathRate"), "deathRate"));
            surgeryRate.add(splitJSONObj(ddesc,caseMap.get("surgeryRate"),"surgeryRate"));
            averageHosDays.add(splitJSONObj(ddesc, caseMap.get("averageHosDays"), "averageHosDays"));
            averageHosCost.add(splitJSONObj(ddesc, caseMap.get("averageHosCost"), "averageHosCost"));
            BigDecimal consumCost1 = (BigDecimal) caseMap.get("consumCost1");
            BigDecimal consumCost2 = (BigDecimal) caseMap.get("consumCost2");
            BigDecimal consumCost3 = (BigDecimal) caseMap.get("consumCost3");
            BigDecimal consumCost = consumCost1.add(consumCost2).add(consumCost3);
            BigDecimal reported = (BigDecimal) caseMap.get("reported");
            DecimalFormat df = new DecimalFormat("0.00");
            String res = df.format(consumCost.divide(reported, 2, BigDecimal.ROUND_HALF_UP));
            averageConsumCost.add(splitJSONObj(ddesc, res, "averageConsumCost"));
            averageMedeCost.add(splitJSONObj(ddesc, caseMap.get("averageMedeCost"), "averageMedeCost"));
            caseMap.put("averageConsumCost", res);
        }

        chartAverHosDatas.add(averageHosDays);

        chartDatas.add(averageHosCost);
        chartDatas.add(averageConsumCost);
        chartDatas.add(averageMedeCost);
        chartDeathAndSurDatas.add(deathRate);
        chartDeathAndSurDatas.add(surgeryRate);

        caseDataObj.put("chartDeathAndSurDatas", chartDeathAndSurDatas);
        caseDataObj.put("chartAverHosDatas", chartAverHosDatas);
        caseDataObj.put("chartDatas", chartDatas);
        caseDataObj.put("tableDates", caseDataMap);
        return caseDataObj;
    }

    @Override
    public List<AnalysisCaseDto> selectLocGroupCaseList(Page<AnalysisCaseDto> page,Map<String, Object> params) {
        String key = (String) params.get("key");
        List<AnalysisCaseDto> analysisCaseDtos = new ArrayList<>();
       if (Objects.equals("reported", key)) {
            //已上报
            analysisCaseDtos = analysisSdsMstaMapper.selectUpTableByTime(page, params);
        }
        return analysisCaseDtos;
    }
}
